/**
 *  @LKAudio LKAudio 对象组件版
 *  @依赖：ES6、CSS3
 *  @BUG反馈：zero@dmlinkong.top（独木林空）
 */

// LKAudio 主程序
function LKAudio(conf) {
  this.audioObj;
  this.lka;
  this.interval;

  // state
  this.state = {
    play: 0,  // 0:stop 1:play 2:pause
    optype: 0,  // 0:null 1:preview
  }
  
  // element
  this.el;
  this.$conf = conf;
  this.$el = conf.el;
  this.lka = lk(this.$el);
  this.$conf.check = conf.check ? conf.check : 250;
  this.audioObj = this.lka.lk('.audio')[0];
  this.audioObj.src = conf.src;


  console.log(
    `%c LKAudio %c Element "${this.$el}" loaded. %c`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
    'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
    'background:transparent'
  );
  /**
  * @描述: LKAudio 构造方法
  * @参数：el => 标签对象, conf => 音频配置
  */


  /**
  * @描述: 加载
  * @参数：src 新的音频地址
  */
  this.load = function (src) {
    return src;
  }

  /**
  * @描述: 播放
  */
 this.play = function () {
    this.state.play = 1;
    this.el.b_paly.hide();
    this.el.b_pause.show();
    this.audioObj.play();
    document.addEventListener("WeixinJSBridgeReady", function () {
      this.audioObj.play();
    }, false);
    document.addEventListener('YixinJSBridgeReady', function () {
      this.audioObj.play();
    }, false);
    this.interval = this.checkTimeStart();

  }

  /**
  * @描述: 暂停
  */
 this.pause = function () {
    this.state.play = 2;
    this.el.b_paly.show();
    this.el.b_pause.hide();
    this.audioObj.pause()
    clearInterval(this.interval);
  }

  /**
  * @描述: 停止
  */
 this.stop = function () {
    this.state.play = 0;
    this.el.b_paly.show();
    this.el.b_pause.hide();
    this.audioObj.pause();
    this.audioObj.currentTime = 0;
    this.el.t_current[0].innerText = '00:00';
    this.el.tl_play[0].style.width = 0;
    this.el.tl_activepoint[0].style.left = 0;
    clearInterval(this.interval);
  }

  this.getMyElement = function () {
    this.el = {
      b_paly: this.lka.lk('.lka-play-button'),
      b_pause: this.lka.lk('.lka-pause-button'),
      t_current: this.lka.lk('.lka-time-current'),
      t_total: this.lka.lk('.lka-time-total'),
      tl_baseline: this.lka.lk('.lka-timeline-baseline'),
      tl_load: this.lka.lk('.lka-timeline-load'),
      tl_play: this.lka.lk('.lka-timeline-play'),
      tl_activepoint: this.lka.lk('.lka-timeline-activepoint'),
    }
  }

  this.checkTimeStart = function () {
    if(this.audioObj.currentTime == 0)
      this.$timeline(0);
    return setInterval(() => {
      let currentTime = this.audioObj.currentTime;
      if (this.state.optype == 0) {
        this.setTimeShow(currentTime);
      }
      this.$timeline(currentTime);
      if(this.audioObj.currentTime == this.audioObj.duration) this.stop();
    }, this.$conf.check);
  }

  this.loadTemplate = function () {
    // 模板
    const template = `
        
        `
  }
  
  this.onPressDown = function (event, type) {
    let box = this.el.tl_baseline[0];

    let disX = box.offsetLeft;
    let zl = event.clientX - 2 - disX;
    if (zl < 0) {
      zl = 0;
    } else if (zl > box.offsetWidth) {
      zl = box.offsetWidth;
    }
    let progress = (zl / this.el.tl_baseline[0].offsetWidth).toFixed(4);
    this.previewTimeShow(progress);
    let currentTime = this.audioObj.duration * progress;
    if (currentTime > this.audioObj.duration) currentTime = this.audioObj.duration;
    this.audioObj.currentTime = currentTime;
  }

 this.onPointerDown = function (event) {
    this.state.optype = 1;
    let self = this;
    let currentTime;
    let box = this.el.tl_baseline[0];
    event.preventDefault();
    let disX = event.clientX - this.el.tl_activepoint[0].offsetLeft;
    document.onmousemove = function (event) {
      let l = event.clientX - disX
      if (l < 0) {
        l = 0;
      } else if (l > box.offsetWidth) {
        l = box.offsetWidth;
      }
      let progress = (l / box.offsetWidth).toFixed(4);
      currentTime = self.audioObj.duration * progress;
      self.previewTimeShow(progress);
    };
    document.onmouseup = function () {
      self.state.optype = 0;
      if (currentTime > self.audioObj.duration) currentTime = self.audioObj.duration;
      self.audioObj.currentTime = currentTime;
      if (self.state.play == 1) {
        clearInterval(self.interval);
        self.interval = self.checkTimeStart();
      }
      self.$timeline(currentTime);
      document.onmousemove = null;
      document.onmouseup = null;
    };
  }

  this.bindEvent = function () {
    this.audioObj.addEventListener('canplay', () => {
      this.el.t_total[0].innerText = this.secondToMin(this.audioObj.duration);
      if (this.$conf.autoplay) this.play();
    });

    this.el.b_paly[0].addEventListener('click', () => {this.play()}); 
    this.el.b_pause[0].addEventListener('click', () => {this.pause()});
    
    // this.el.tl_activepoint[0].addEventListener('touchstart', this.onPointerDown);
    // this.el.tl_activepoint[0].addEventListener('mousedown', this.onPointerDown);
    // this.el.tl_activepoint[0].addEventListener('touchstart', (event) => {this.onPointerDown(event, 1)});
    // this.el.tl_activepoint[0].addEventListener('mousedown', (event) => {this.onPointerDown(event, 1)});

    // this.el.tl_load[0].addEventListener('touchstart', (event) => {this.onPressDown(event, 0)});
    // this.el.tl_play[0].addEventListener('touchstart', (event) => {this.onPressDown(event, 0)});
    this.el.tl_load[0].addEventListener('click', (event) => {this.onPressDown(event, 0)});
    this.el.tl_play[0].addEventListener('click', (event) => {this.onPressDown(event, 0)});
  }

  this.previewTimeShow = function (progress) {
    let playTime = this.secondToMin(this.audioObj.duration * progress);
    let width = this.el.tl_baseline[0].offsetWidth;
    this.el.t_current[0].innerText = playTime;
    this.el.tl_play[0].style.width = progress * 100 + "%";
    this.el.tl_activepoint[0].style.left = width * progress + "px";
  }

  this.setTimeShow = function (t) {
    t = Math.floor(t);
    let playTime = this.secondToMin(this.audioObj.currentTime);
    let progress = (t / this.audioObj.duration).toFixed(4);
    let width = this.el.tl_baseline[0].offsetWidth;
    this.el.t_current[0].innerText = playTime;
    this.el.t_total[0].innerText = this.secondToMin(this.audioObj.duration);
    this.el.tl_play[0].style.width = progress * 100 + "%";
    this.el.tl_activepoint[0].style.left = width * progress + "px";
  }

  this.secondToMin = function (s) {
    var MM = Math.floor(s / 60);
    var SS = s % 60;
    if (MM < 10)
        MM = "0" + MM;
    if (SS < 10)
        SS = "0" + SS;
    var min = MM + ":" + SS;
    return min.split('.')[0];
  }

  if (this.$conf.autoplay) this.audioObj.autoplay = true;

  this.$timeline = conf.timeline ? conf.timeline : (t) => {};
  // this.interval = this.checkTimeStart();

  this.getMyElement();
  this.loadTemplate();
  this.bindEvent();
}

// LKDom 主程序
window.LKDom = (s) => {
  let lkd = {}
  if (typeof s === 'string') {
    let temp = document.querySelectorAll(s);
    for (let i = 0; i < temp.length; i++) {
      lkd[i] = temp[i];
    }
    lkd.length = temp.length;
  } else if (s instanceof Node) {
    lkd = {
      0: s,
      length: 1
    }
  }

  lkd.show = () => {
    for(let i = 0 ; i<lkd.length; i++){
      const classlist = lkd[i].classList;
      classlist.remove('hide');
      classlist.add('show');
    }
  }

  lkd.hide = () => {
    for(let i = 0 ; i<lkd.length; i++){
      const classlist = lkd[i].classList;
      classlist.remove('show');
      classlist.add('hide');
    }
  }

  // 支持链式编程
  lkd.lk = LKDom;

  return lkd;
}

window.lk = LKDom;

(() => {
  // console.log('预加载');
})()
